package com.guoranhao.tool.utils;


import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.guoranhao.tool.conf.OssConfig;
import com.guoranhao.tool.enums.FileUploadSourceEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

/**
 * @version 1.0  2017/9/30 15:43   by  马双亮（masl@cloud-young.com）创建
 * @Descpription:oss上传图片
 */
public class OssFileUtils {

    private static Logger logger = LoggerFactory.getLogger(OssFileUtils.class);

    /**
     * @param source
     * @param fileType
     * @param in
     * @return
     * @Descpription:
     * @version 1.0  2017/10/9 15:06   by  马双亮（masl@cloud-young.com）创建
     */
    public static String uploadFile(int source, String fileName, String fileType, InputStream in, long tid) {
        return uploadFile(source, fileName, fileType, in, null, tid);
    }

    /**
     * @param source
     * @param fileType
     * @param in
     * @param map
     * @return
     * @throws OSSException
     * @throws ClientException
     * @throws FileNotFoundException
     * @Descpription:上传文件
     * @version 1.0  2017/9/21 15:27   by  马双亮（masl@cloud-young.com）创建
     */
    public static String uploadFile(int source, String fileName, String fileType, InputStream in, Map<String, String> map, long tid) {
        long start = System.currentTimeMillis();
        logger.info("uploadFile-" + tid + "-文件上传开始时间：{}", start);
        if (StringUtils.isEmpty(fileName)) {
            StringBuffer sb = new StringBuffer(DateUtils.formatDate(new Date(), "yyyyMMddhhmmss"));
            sb.append("-");
            sb.append(md5(UUIDUtil.uuid() + tid));
            sb.append(".");
            sb.append(fileType);
            fileName = sb.toString();
        }

        String ossEndpoint = (map == null || StringUtils.isEmpty(map.get("ossEndpoint"))) ? OssConfig.getEndpoint() : map.get("ossEndpoint");
        String ossAccessId = (map == null || StringUtils.isEmpty(map.get("ossAccessId"))) ? OssConfig.getAccessId() : map.get("ossAccessId");
        String ossAccessKey = (map == null || StringUtils.isEmpty(map.get("ossAccessKey"))) ? OssConfig.getAccessKey() : map.get("ossAccessKey");
        String ossBucketName = (map == null || StringUtils.isEmpty(map.get("ossBucketName"))) ? OssConfig.getOssBucketName() : map.get("ossBucketName");
        String folder = FileUploadSourceEnum.getFolderNameBySource(source);
        // 创建ClientConfiguration实例
        ClientConfiguration conf = new ClientConfiguration();
        conf.setMaxConnections(OssConfig.getMaxConnections());
        conf.setSocketTimeout(OssConfig.getSocketTimeout());
        conf.setMaxErrorRetry(OssConfig.getMaxErrorRetry());
        OSSClient ossClient = null;
        fileName = (folder + "/" + fileName).toLowerCase();
        try {
            ossClient = new OSSClient(ossEndpoint, ossAccessId, ossAccessKey, conf);
            logger.info("uploadFile-" + tid + "-文件上传参数:{}", ossEndpoint + "|*|" + ossAccessId + "|*|" + ossAccessKey + "|*|" + ossBucketName);
            PutObjectResult putObjectResult = ossClient.putObject(ossBucketName, fileName, in);
            logger.info("uploadFile-" + tid + "-文件上传返回：{}", JSON.toJSONString(putObjectResult));
            logger.info("uploadFile-" + tid + "-文件上传结束时间：{},耗时{}ms", System.currentTimeMillis(), System.currentTimeMillis() - start);
            return fileName;
        } catch (Exception oe) {
            logger.error("uploadFile-" + tid + "-文件上传异常", oe);
            return "";
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ossClient.shutdown();
        }
    }

    private static String fileUrl(String ossEndpoint, String ossBucketName, String fileName) {
        int index = ossEndpoint.indexOf("://");
        StringBuffer buffer = new StringBuffer(ossEndpoint.substring(0, index));
        buffer.append("://")
                .append(ossBucketName)
                .append(".")
                .append(ossEndpoint.substring(index + 3, ossEndpoint.length()))
                .append("/")
                .append(fileName);
        return buffer.toString();
    }

    /**
     * 使用guava的MD5提现
     *
     * @param dueStr
     * @return
     */
    public static String md5(String dueStr) {
        byte[] md5 = Hashing.md5().hashString(dueStr, Charsets.UTF_8).asBytes();
        return byte2hex(md5);
    }

    /**
     * 二行制转字符串
     */
    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer();
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs.append("0").append(stmp);
            } else {
                hs.append(stmp);
            }
        }
        return hs.toString().toUpperCase();
    }
}